package com.sina.shop.controller.admin;

import com.sina.shop.core.exception.server.UpdateException;
import com.sina.shop.domain.admin.Admin;
import com.sina.shop.service.admin.AdminService;
import com.sina.shop.web.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * 段浩杰   2018-04-12-16:49
 */
@Controller
@RequestMapping("/shop-web/admin")
public class AdminController extends BaseController {

    @Autowired
    private AdminService adminService;

    @RequestMapping(value = "getAdmin", method = RequestMethod.GET)
    public ModelAndView getAdmin(String account) {
        LOG.info("account:{}", account);
        ModelAndView mv = new ModelAndView("commonView");
        Admin admin = adminService.getAdmin(account);
        mv.addObject(RESULT, admin);
        return mv;
    }

    @RequestMapping(value = "updateAdmin", method = RequestMethod.POST)
    public ModelAndView updateAdmin(Admin admin) {
        LOG.info("admin:{}", admin);

        ModelAndView mv = new ModelAndView("commonView");
        Map<String, Object> result = new HashMap<>(4);
        try {
            adminService.updateAdmin(admin);
            result.put(CODE, OK);
            result.put(MSG, "更新用户成功");
        } catch (UpdateException e) {
            LOG.info("更新用户出现异常:{}", e.getMessage());
            result.put(CODE, e.getResultCode());
            result.put(MSG, e.getMessage());
        }

        mv.addObject(RESULT, result);
        return mv;
    }

    @RequestMapping(value = "saveAdmin", method = RequestMethod.POST)
    public ModelAndView saveAdmin(Admin admin) {
        LOG.info("admin:{}", admin);

        ModelAndView mv = new ModelAndView("commonView");
        Map<String, Object> result = new HashMap<>(4);
        try {
            adminService.saveAdmin(admin);
            result.put(CODE, OK);
            result.put(MSG, "新增用户成功");
        } catch (UpdateException e) {
            LOG.info("新增用户出现异常:{}", e.getMessage());
            result.put(CODE, e.getResultCode());
            result.put(MSG, e.getMessage());
        }

        mv.addObject(RESULT, result);
        return mv;
    }
}
